﻿using System;
using System.ServiceProcess;
using System.Timers;
using Driven.ProcessScheduler.WindowsService.Lib;

namespace Driven.ProcessScheduler.WindowsService
{
    public partial class SchedulingEngine : ServiceBase
    {
        readonly ILogger _logger;
        readonly IScheduleManager _scheduleManager;
        readonly Timer _timer;

        public SchedulingEngine(IScheduleManager scheduleManager, ILogger logger)
        {
            InitializeComponent();
            _scheduleManager = scheduleManager;
            _logger = logger;
            _timer = new Timer(60000d);
            _timer.Elapsed += ServiceTimer_Tick;
        }

        #region Service Control

        protected override void OnStart(string[] args)
        {
            try
            {
                startService();
            }
            catch (Exception ex)
            {
                _logger.Log(ex.ToString());
            }
        }
        protected override void OnStop()
        {
            _timer.AutoReset = false;
            _timer.Enabled = false;
            _logger.Log("Service Stopped");
        }
        protected override void OnPause()
        {
            _timer.Stop();
            _logger.Log("Service Paused");
        }
        protected override void OnContinue()
        {
            _timer.Start();
            _logger.Log("Service Continued");
        }

        #endregion

        private void startService()
        {
            _timer.AutoReset = true;
            _timer.Enabled = true;
            _timer.Start();

            logStartupInformation();
        }

        private void ServiceTimer_Tick(object sender, ElapsedEventArgs e)
        {
            _timer.Stop();
            string[] logMessages = _scheduleManager.Execute().ToArray();
            _logger.Log(logMessages);
            _timer.Start();
        }

        private void logStartupInformation()
        {
            _logger.Log("Service Started");

            if (_scheduleManager.Schedules.Count == 0)
            {
                _logger.Log("No schedules have been configured");
                return;
            }

            _logger.Log("The following services have been configured:");

            _scheduleManager.Schedules.ForEach(s =>
                    {
                        if (s.TimeSchedule.Ticks != 0) _logger.Log(string.Format("{0}, running at {1}", s.Component.ToString(), s.TimeSchedule));
                        if (s.RepetitionSchedule != 0) _logger.Log(string.Format("{0}, repeating every {1} minutes", s.Component.ToString(), s.RepetitionSchedule));
                    });
        }
    }
}